class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 2;)
        {
            int left = i + 1;
            int right = nums.size() - 1;
            while (left < right)
            {
                int sum = nums[left] + nums[right];
                if (sum < -nums[i])
                    left++;
                else if (sum > -nums[i])
                    right--;
                else
                {
                    ret.push_back({ nums[i],nums[left],nums[right] });
                    left++;
                    right--;
                    while (nums[left] == nums[left - 1] && left < right)
                    {
                        left++;
                    }
                    while (nums[right] == nums[right + 1] && left < right)
                    {
                        right--;
                    }
                }

            }
            i++;
            while (nums[i] == nums[i - 1] && i < nums.size() - 2)
            {
                i++;
            }
        }
        return ret;
    }
};